//
//  LJLocationManager.m
//  DriverClient
//
//  Created by 吕晶 on 2020/11/13.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "LJLocationManager.h"
#import <CoreLocation/CoreLocation.h>
#import "LocationAlertView.h"

@interface LJLocationManager ()<CLLocationManagerDelegate,AMapLocationManagerDelegate> {
    CLLocation *currentLocation;
    BOOL on_way;//司机是否在途中，是则上传位置
    int location_time;//位置上传的频率
    int location_distance;//多少米内的点不重复上传
}

@property (nonatomic,strong) CLLocationManager *location;
//@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic,strong) AMapLocationManager *amapLocation;

@end

static LJLocationManager *manager;
static dispatch_once_t once;

@implementation LJLocationManager

-(AMapLocationManager *)amapLocation {
    if (!_amapLocation) {
        _amapLocation = [[AMapLocationManager alloc] init];
        _amapLocation.delegate = self;
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [_amapLocation setDesiredAccuracy:kCLLocationAccuracyBest];
        //   定位超时时间，最低2s，此处设置为10s
        _amapLocation.locationTimeout = 2;
        //   逆地理请求超时时间，最低2s，此处设置为10s
        _amapLocation.reGeocodeTimeout = 2;
        _amapLocation.distanceFilter = 2;
    }
    return _amapLocation;
}

-(CLLocationManager *)location {
    if (!_location) {
        _location = [[CLLocationManager alloc] init];
        _location.delegate = self;
        _location.desiredAccuracy = kCLLocationAccuracyBest;//导航级别的精确度
//        _location.allowsBackgroundLocationUpdates = YES; //允许后台刷新
        _location.pausesLocationUpdatesAutomatically = NO; //不允许自动暂停刷新
        _location.distanceFilter = kCLDistanceFilterNone;  //不需要移动都可以刷新
    }
    return _location;
}

//-(NSTimer *)timer {
//    if (!_timer) {
//        _timer = [NSTimer scheduledTimerWithTimeInterval:location_time target:self selector:@selector(amapUpdateLocation) userInfo:nil repeats:YES];
//    }
//    return _timer;;
//}

//上传位置信息
- (void)amapUpdateLocation {
    if ([User isLogin]) {
        if (on_way) {
//            double Last_Latitude = [[USER_D objectForKey:@"Last_Latitude"] doubleValue];
//            double Last_Longitude = [[USER_D objectForKey:@"Last_Longitude"] doubleValue];
//            if (Last_Latitude && Last_Longitude) {
//                CLLocation *lastLocation = [[CLLocation alloc] initWithLatitude:Last_Latitude longitude:Last_Longitude];
//                CLLocationDistance distance = [lastLocation distanceFromLocation:currentLocation];
//                if (distance < location_distance) {
//                    return;
//                }
//            }
//            __weak_self;
//            [HttpRequest PostWithApi:DriverClientUpDateDriverLocation params:@{@"lat":@(currentLocation.coordinate.latitude),@"lng":@(currentLocation.coordinate.longitude)} progress:^(NSProgress * _Nonnull progress) {
//
//            } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
//                __strong_self;
//                if (code) {
//                    NSLog(@"位置上传成功 经度=%f 纬度=%f",strongSelf->currentLocation.coordinate.latitude,strongSelf->currentLocation.coordinate.longitude);
//                    [USER_D setObject:@(strongSelf->currentLocation.coordinate.latitude) forKey:@"Last_Latitude"];
//                    [USER_D setObject:@(strongSelf->currentLocation.coordinate.longitude) forKey:@"Last_Longitude"];
//                }
//            } fail:^(NSError * _Nonnull error) {
//
//            }];
        }
    }
}

+ (LJLocationManager *)shareManager {
    dispatch_once(&once, ^ {
        manager = [[LJLocationManager alloc] init];
    });
    return manager;
}

+ (void)userRelease {
    once = 0;
    manager = nil;
}

- (instancetype)init {
    if (self = [super init]) {
        on_way = NO;
        location_time = 10;//默认10s上传一次位置
        location_distance = 10;//默认10米范围内的位置不重复上传
    }
    return self;
}

//判断是否在途中
- (void)requestForOnWay {
    if ([User isLogin]) {
//        [HttpRequest PostWithApi:DriverClientDriverIsOnWay params:@{} progress:^(NSProgress * _Nonnull progress) {
//
//        } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
//            if (code) {
//                self->on_way = [[responseObject objectForKey:@"on_way"] boolValue];
//                int time = [[responseObject objectForKey:@"location_time"] intValue];
//                if (time) {
//                    self->location_time = time;
//                }
//                int distance = [[responseObject objectForKey:@"location_distance"] intValue];
//                if (distance) {
//                    self->location_distance = distance;
//                }
//                if (self->on_way) {
//                    [self amapUpdateLocation];
//                    if (self.timer) {
//                        [self.timer invalidate];
//                        self.timer = nil;
//                    }
//                    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
//                }else {
//                    if (self.timer) {
//                        [self.timer invalidate];
//                        self.timer = nil;
//                    }
//                }
//            }
//        } fail:^(NSError * _Nonnull error) {
//
//        }];
    }
}

- (void)requestForAuth {
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        //用户未决定是否使用定位服务
        [self.location requestAlwaysAuthorization];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted) {
        //定位服务受限
        [[LocationAlertView shareAlert] showInView:MAIN_WINDOW];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        //定位服务被禁止
        [[LocationAlertView shareAlert] showInView:MAIN_WINDOW];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
        //定位服务被始终允许
        [self.amapLocation startUpdatingLocation];
//        [self requestForOnWay];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
        //定位服务被仅使用app时允许
        [self.amapLocation startUpdatingLocation];
//        [self requestForOnWay];
    }
}

- (void)uploadLocationWithSource:(NSString *)source withUser_id:(NSString *)user_id {
//    __weak_self;
//    [self.amapLocation requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        if (error) {
//            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//            if (error.code == AMapLocationErrorLocateFailed) {
//                return;
//            }
//        }
//        NSLog(@"location:%@", location);
//        if (regeocode) {
//            NSLog(@"reGeocode:%@", regeocode);
//        }
//        [weakself requestForUploadLocation:location WithSource:source withUser_id:user_id];
//    }];
    [self requestForUploadLocation:currentLocation WithSource:source withUser_id:user_id];
}

- (void)requestForUploadLocation:(CLLocation *)location WithSource:(NSString *)source withUser_id:(NSString *)user_id {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (user_id.length) {
        [dic setObject:user_id forKey:@"user_id"];
    }
    if (source.length) {
        [dic setObject:source forKey:@"source"];
    }
//    [dic setObject:[User getUserID] forKey:@"sw_id"];
    if (location.coordinate.latitude) {
        [dic setObject:@(location.coordinate.latitude) forKey:@"lat"];
    }
    if (location.coordinate.longitude) {
        [dic setObject:@(location.coordinate.longitude) forKey:@"lng"];
    }
    [HttpRequest PostWithApi:LogisticsSupplierTaskGetDriverUploadLocation params:dic progress:^(NSProgress * _Nonnull progress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            NSLog(@"司机位置上传成功");
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location {
    if (location.horizontalAccuracy != -1 && location.verticalAccuracy != -1) {
        currentLocation = location;
        NSLog(@"高德位置 经度=%f 纬度=%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    }
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//    CLLocation *currentLocation = [locations lastObject];
////    if (!coordinate.latitude) {
////        //用户首次授权成功，就开始获取位置信息
//        if (![WGS84TOGCJ02 isLocationOutOfChina:[currentLocation coordinate]]) {
//            //转换后的coord
//            coordinate = [WGS84TOGCJ02 transformFromWGSToGCJ:[currentLocation coordinate]];
//        }else {
//            coordinate = currentLocation.coordinate;
//        }
////    }
////    if (currentLocation.speed != -1 && currentLocation.horizontalAccuracy != -1 && currentLocation.verticalAccuracy != -1) {
////        //判断是不是属于国内范围
////        if (![WGS84TOGCJ02 isLocationOutOfChina:[currentLocation coordinate]]) {
////            //转换后的coord
////            coordinate = [WGS84TOGCJ02 transformFromWGSToGCJ:[currentLocation coordinate]];
////        }else {
////            coordinate = currentLocation.coordinate;
////        }
////        NSLog(@"原生位置 经度=%f 纬度=%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
////    }
//    NSLog(@"原生位置 经度=%f 纬度=%f",coordinate.latitude,coordinate.longitude);
}

- (CLLocationCoordinate2D)getCurrentLocation {
    return currentLocation.coordinate;
}

@end
